//! 系统集成测试
//! 
//! 测试各个模块之间的集成和交互

use std::sync::Arc;
use tokio::time::{sleep, Duration};

use data_gateway_kernel::{DataGatewayKernel, Query, QueryType};
use data_gateway_kernel::query::{QueryOptions, QueryContext};
use data_gateway_parser::{ScriptParser, ScriptExecutor, ScriptContext};
use data_gateway_flight_sql::{FlightSqlServer, FlightSqlServerConfig};
use data_gateway_gateway::{HttpServer, HttpServerConfig};

/// 创建测试用的内核实例
async fn create_test_kernel() -> anyhow::Result<Arc<DataGatewayKernel>> {
    let kernel = Arc::new(DataGatewayKernel::new().await?);
    Ok(kernel)
}

/// 创建测试查询
fn create_test_query(id: &str, query_type: QueryType, content: &str) -> Query {
    Query {
        id: id.to_string(),
        query_type,
        content: content.to_string(),
        parameters: std::collections::HashMap::new(),
        options: QueryOptions::default(),
        context: QueryContext::default(),
    }
}

#[tokio::test]
async fn test_kernel_parser_integration() -> anyhow::Result<()> {
    // 测试内核和解析器的集成
    let kernel = create_test_kernel().await?;
    let parser = ScriptParser::new();
    let mut executor = ScriptExecutor::new();
    let mut context = ScriptContext::new();

    // 解析脚本
    let script = "let x = 10; x * 2";
    let program = parser.parse(script)?;
    
    // 执行脚本
    let result = executor.execute_with_context(program, &mut context).await?;
    
    // 验证结果
    assert!(result.stats.duration_ms >= 0);
    
    // 测试内核查询处理
    let query = create_test_query("test_1", QueryType::Script, script);
    let query_result = kernel.handle_query(query).await?;
    
    assert!(query_result.stats.duration_ms >= 0);
    
    Ok(())
}

#[tokio::test]
async fn test_kernel_flight_sql_integration() -> anyhow::Result<()> {
    // 测试内核和Flight SQL的集成
    let kernel = create_test_kernel().await?;
    
    // 创建Flight SQL服务器配置
    let config = FlightSqlServerConfig {
        host: "127.0.0.1".to_string(),
        port: 50052, // 使用不同端口避免冲突
        enable_tls: false,
        max_connections: 100,
        request_timeout_seconds: 10,
    };
    
    // 创建Flight SQL服务器
    let server = FlightSqlServer::new(config, kernel.clone());
    
    // 在后台启动服务器
    let server_handle = tokio::spawn(async move {
        // 运行一小段时间后停止
        sleep(Duration::from_millis(100)).await;
        Ok::<(), anyhow::Error>(())
    });
    
    // 等待服务器启动
    sleep(Duration::from_millis(50)).await;
    
    // 测试内核查询
    let query = create_test_query("test_flight", QueryType::Sql, "SELECT 1");
    let result = kernel.handle_query(query).await?;
    
    assert!(result.stats.duration_ms >= 0);
    
    // 等待服务器任务完成
    server_handle.await??;
    
    Ok(())
}

#[tokio::test]
async fn test_kernel_http_gateway_integration() -> anyhow::Result<()> {
    // 测试内核和HTTP网关的集成
    let kernel = create_test_kernel().await?;
    
    // 创建HTTP服务器配置
    let config = HttpServerConfig {
        host: "127.0.0.1".to_string(),
        port: 8081, // 使用不同端口避免冲突
        enable_cors: true,
        request_timeout_seconds: 10,
    };
    
    // 创建HTTP服务器
    let server = HttpServer::new(config, kernel.clone());
    
    // 测试路由创建
    let _router = server.create_router();
    
    // 测试内核查询
    let query = create_test_query("test_http", QueryType::Sql, "SELECT 1");
    let result = kernel.handle_query(query).await?;
    
    assert!(result.stats.duration_ms >= 0);
    
    Ok(())
}

#[tokio::test]
async fn test_full_system_integration() -> anyhow::Result<()> {
    // 测试完整系统集成
    let kernel = create_test_kernel().await?;
    
    // 测试多种查询类型
    let queries = vec![
        create_test_query("sql_test", QueryType::Sql, "SELECT 1"),
        create_test_query("script_test", QueryType::Script, "1 + 2"),
        create_test_query("graphql_test", QueryType::GraphQL, "{ test }"),
    ];
    
    for query in queries {
        let result = kernel.handle_query(query).await?;
        assert!(result.stats.duration_ms >= 0);
    }
    
    // 测试并发查询
    let mut handles = Vec::new();
    
    for i in 0..5 {
        let kernel = kernel.clone();
        let handle = tokio::spawn(async move {
            let query = create_test_query(
                &format!("concurrent_test_{}", i),
                QueryType::Sql,
                "SELECT 1"
            );
            kernel.handle_query(query).await
        });
        handles.push(handle);
    }
    
    // 等待所有查询完成
    for handle in handles {
        let result = handle.await??;
        assert!(result.stats.duration_ms >= 0);
    }
    
    Ok(())
}

#[tokio::test]
async fn test_error_handling_integration() -> anyhow::Result<()> {
    // 测试错误处理集成
    let kernel = create_test_kernel().await?;
    
    // 测试无效查询
    let invalid_query = create_test_query("invalid", QueryType::Sql, "INVALID SQL");
    let result = kernel.handle_query(invalid_query).await;
    
    // 应该返回错误，但不应该崩溃
    assert!(result.is_err() || result.is_ok());
    
    // 测试空查询
    let empty_query = create_test_query("empty", QueryType::Sql, "");
    let result = kernel.handle_query(empty_query).await;
    
    // 应该能够处理空查询
    assert!(result.is_err() || result.is_ok());
    
    Ok(())
}

#[tokio::test]
async fn test_performance_integration() -> anyhow::Result<()> {
    // 测试性能集成
    let kernel = create_test_kernel().await?;
    
    let start_time = std::time::Instant::now();
    
    // 执行多个查询测试性能
    for i in 0..100 {
        let query = create_test_query(
            &format!("perf_test_{}", i),
            QueryType::Sql,
            "SELECT 1"
        );
        let _result = kernel.handle_query(query).await?;
    }
    
    let elapsed = start_time.elapsed();
    
    // 验证性能指标
    assert!(elapsed.as_millis() < 5000); // 100个查询应该在5秒内完成
    
    let avg_time_per_query = elapsed.as_millis() as f64 / 100.0;
    assert!(avg_time_per_query < 50.0); // 平均每个查询应该在50ms内完成
    
    println!("平均查询时间: {:.2}ms", avg_time_per_query);
    
    Ok(())
}

#[tokio::test]
async fn test_memory_usage_integration() -> anyhow::Result<()> {
    // 测试内存使用集成
    let kernel = create_test_kernel().await?;
    
    // 执行大量查询测试内存使用
    for i in 0..1000 {
        let query = create_test_query(
            &format!("memory_test_{}", i),
            QueryType::Sql,
            "SELECT 1"
        );
        let _result = kernel.handle_query(query).await?;
        
        // 每100个查询检查一次
        if i % 100 == 0 {
            // 这里可以添加内存使用检查
            // 目前只是确保系统仍然响应
            let stats = kernel.get_stats().await?;
            assert!(stats.queries_processed >= i as u64);
        }
    }
    
    Ok(())
}

#[tokio::test]
async fn test_concurrent_access_integration() -> anyhow::Result<()> {
    // 测试并发访问集成
    let kernel = create_test_kernel().await?;
    
    // 创建多个并发任务
    let mut handles = Vec::new();
    
    for i in 0..20 {
        let kernel = kernel.clone();
        let handle = tokio::spawn(async move {
            for j in 0..10 {
                let query = create_test_query(
                    &format!("concurrent_{}_{}", i, j),
                    QueryType::Sql,
                    "SELECT 1"
                );
                let _result = kernel.handle_query(query).await?;
            }
            Ok::<(), anyhow::Error>(())
        });
        handles.push(handle);
    }
    
    // 等待所有任务完成
    for handle in handles {
        handle.await??;
    }
    
    // 验证统计信息
    let stats = kernel.get_stats().await?;
    assert!(stats.queries_processed >= 200); // 20 * 10 = 200个查询
    
    Ok(())
}
